package org.kongqian.orgs.service.impl;

import org.kongqian.basic.service.impl.BaseServiceImpl;
import org.kongqian.orgs.domain.Department;
import org.kongqian.orgs.mapper.DepartmentMapper;
import org.kongqian.orgs.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public void insert(Department department) {
        department.setCreate_time(new Date());
        //做保存path的功能实现
        super.insert(department);//新增返回自身主键id
        Long id = department.getId();
        //由祖先id+自己的id来获得path
        //判断自己的id时候有父级id
        String path="";
        if (department.getParent().getId()==null){
            //进去这里说明没有父级部门
            path="/"+id;
        }else {
            //通过父部门id去查父部门的path
            Department department1 = departmentMapper.selectById(department.getParent().getId());
            path = department1.getPath()+"/"+id;
        }
        //如果没有就是一级部门
        //如果有就祖先id+自己的id
        department.setPath(path);
        super.updateById(department);
        System.out.println(path);
    }

    @Override
    public void updateById(Department department) {
        department.setUpdate_time(new Date());
        String path="";
        Long id = department.getId();
        if (department.getParent().getId()==null){
            //进去这里说明没有父级部门
            path="/"+id;
        }else {
            //通过父部门id去查父部门的path
            Department department1 = departmentMapper.selectById(department.getParent().getId());
            path = department1.getPath()+"/"+id;
        }
        //修改
        department.setPath(path);
        super.updateById(department);
    }

    @Override
    public List<Department> getDepartmentTree() {
        return departmentMapper.getDepartmentTree();
    }

    @Override
    @Transactional
    public void batchDeleteDept(List<Long> ids) {
        departmentMapper.batchDeleteDept(ids);
    }
}
